package com.jiegui.payinterface.handler.impl.wxpay.utils;


import org.apache.commons.lang3.StringUtils;

import java.security.MessageDigest;
import java.util.Objects;

/**
 * MD5工具类
 *
 * @author wuqicheng
 * @date 2021/3/10
 */
public class MD5 {

    private final static String[] hexDigits = {"0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};

    /**
     * 转换字节数组为16进制字串
     *
     * @param b 字节数组
     * @return 16进制字串
     */

    public static String byteArrayToHexString(byte[] b) {
        StringBuilder resultSb = new StringBuilder();
        for (byte value : b) {
            resultSb.append(byteToHexString(value));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n = 256 + n;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public final static String MD5Encode16(String s) {
        return Objects.requireNonNull(MD5Encode(s)).substring(6, 22);
    }

    public final static String MD5Encode(String s, String charset) {
        StringBuilder sb = new StringBuilder();
        try {
            byte[] btInput = s.getBytes(charset);
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            for (byte b : md) {
                int val = ((int) b) & 0xff;
                if (val < 16) {
                    sb.append("0");
                }
                sb.append(Integer.toHexString(val));
            }
        } catch (Exception e) {
            return null;
        }
        return sb.toString();
    }


    public static String MD5Encode(String origin) {
        byte [] bytes;
        if (StringUtils.isNotBlank(origin)) {
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                bytes = md.digest(origin.getBytes());
                if(bytes != null){
                    return byteArrayToHexString(bytes);
                }
            } catch (Exception ignored) {

            }
        }
        return null;
    }


}
